package sxkyxt.kjyxgs.cn.ishop_gather_uploading_android;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.os.StrictMode;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @version V1.0 <描述当前版本功能>.
 * @filename: sxkyxt.kjyxgs.cn.ishop_gather_uploading_android
 * @Author HY  on {Administrator}.
 * @Org 山西科远信通科技有限公司.
 * @Description: ${TODO} .
 * @Motto 大梦谁先觉, 贫僧我自知..
 * @Date 2018/11/28
 */
public class UploadActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    private static final String TAG = "UploadActivity";

    private Spinner mActivityUploadShowProductTypeListSpinner;
    private Spinner mActivityUploadShowVarietiesTypeListSpinner;
    private TextView mActivityUploadShowProductNameText;
    private TextView mActivityUploadShowProductSizeText;
    private TextView mActivityUploadShowProductPriceText;
    private ImageView mActivityUploadShowProductPhotoImage;
    private ImageView mActivityUploadShowProductBarcodeImage;
    private Button mActivityUploadClickProductSubmitButton;
    private GridView photos_gv;
    private GridView photos_gv_barcode;
    private TextView mActivityUploadShowProductBarcodeTextText;

    private String status = Environment.getExternalStorageState();
    private String localTempImgDir = "ishop_gather_upload";
    private String localTempImgFileName;
    private int gid;
    private PopupWindow popupWindow;
    private Map<Integer, String> mHashMap;
    private Map<Integer, String> mHashMapBarcode;


    private LoginBean loginBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        initView();
        initSettings();
        initContent();
    }

    private void initSettings() {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            builder.detectFileUriExposure();
        }
    }

    private void initContent() {
        OkHttpEngine.getInstance().getAsynHttp(CONSTS.HOST + CONSTS.LISTBYPARENTID + "?parent_id=0", this).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UploadActivity.this, R.string.get_type_list, Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                final String result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(result)) {
                            Gson gson = new GsonBuilder().create();
                            GoodStype goodStype = gson.fromJson(result, GoodStype.class);
                            GoodStype.ExtendBean extendBean = goodStype.getExtend();
                            List<GoodStype.ExtendBean.GoodsTypesBean> goodsTypesBeanList = extendBean.getGoods_Types();
                            Array_Adapter array_adapter = new Array_Adapter(goodsTypesBeanList, UploadActivity.this);
                            mActivityUploadShowProductTypeListSpinner.setAdapter(array_adapter);

                        } else {
                            Toast.makeText(UploadActivity.this, R.string.result_data_null, Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
    }

    private void initView() {
        loginBean = getIntent().getParcelableExtra("loginRequestData");
        mActivityUploadShowProductTypeListSpinner = (Spinner) findViewById(R.id.spinner_activity_upload_show_product_type_list);
        mActivityUploadShowProductTypeListSpinner.setOnItemSelectedListener(this);
        mActivityUploadShowVarietiesTypeListSpinner = (Spinner) findViewById(R.id.spinner_activity_upload_show_varieties_type_list);
        mActivityUploadShowProductNameText = (TextView) findViewById(R.id.text_activity_upload_show_product_name);
        mActivityUploadShowProductSizeText = (TextView) findViewById(R.id.text_activity_upload_show_product_size);
        mActivityUploadShowProductPriceText = (TextView) findViewById(R.id.text_activity_upload_show_product_price);
        mActivityUploadShowProductPhotoImage = (ImageView) findViewById(R.id.image_activity_upload_show_product_photo);
        mActivityUploadShowProductPhotoImage.setOnClickListener(this);
        mActivityUploadShowProductBarcodeImage = (ImageView) findViewById(R.id.image_activity_upload_show_product_barcode);
        mActivityUploadShowProductBarcodeImage.setOnClickListener(this);
        mActivityUploadShowProductBarcodeImage.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                IntentIntegrator integrator = new IntentIntegrator(UploadActivity.this);
//                // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
                integrator.setCaptureActivity(ScanActivity.class); //设置打开摄像头的Activity
                integrator.setPrompt("请扫描ISBN"); //底部的提示文字，设为""可以置空
                integrator.setCameraId(0); //前置或者后置摄像头
                integrator.setBeepEnabled(true); //扫描成功的「哔哔」声，默认开启
                integrator.setBarcodeImageEnabled(true);
                integrator.initiateScan();
                return true;
            }
        });
        mActivityUploadClickProductSubmitButton = (Button) findViewById(R.id.button_activity_upload_click_product_submit);
        mActivityUploadClickProductSubmitButton.setOnClickListener(this);
        mActivityUploadShowProductBarcodeTextText = (TextView) findViewById(R.id.text_activity_upload_show_product_barcode_text);
        photos_gv = (GridView) findViewById(R.id.report_gv_photos);
        photos_gv_barcode = (GridView) findViewById(R.id.report_gv_photos_Barcode);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_activity_upload_click_product_submit:
                // TODO 18/11/28
                if (TextUtils.isEmpty(mActivityUploadShowProductNameText.getText().toString())) {
                    Toast.makeText(UploadActivity.this, R.string.upload_activity_item_three_test_text, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(mActivityUploadShowProductSizeText.getText().toString())) {
                    Toast.makeText(UploadActivity.this, R.string.upload_activity_item_four_test_text, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(mActivityUploadShowProductPriceText.getText().toString())) {
                    Toast.makeText(UploadActivity.this, R.string.upload_activity_item_five_test_text, Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(mActivityUploadShowProductBarcodeTextText.getText().toString())) {
                    Toast.makeText(UploadActivity.this, R.string.upload_activity_item_input_barcode, Toast.LENGTH_SHORT).show();
                    return;
                }

                if (mHashMap == null) {
                    Toast.makeText(UploadActivity.this, R.string.upload_activity_item_input_barcode, Toast.LENGTH_SHORT).show();
                    return;
                }

                if (mHashMapBarcode == null) {
                    Toast.makeText(UploadActivity.this, R.string.upload_activity_item_input_barcode_photo, Toast.LENGTH_SHORT).show();
                    return;
                }

                MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                if (mHashMap != null) {

                    final List<Integer> list_key = toHashKeyOrList(mHashMap);
                    for (int i = 0; i < mHashMap.size(); i++) {
                        File f = new File(mHashMap.get(list_key.get(i)));
                        builder.addFormDataPart("pic1", f.getName(), RequestBody.create(OkHttpEngine.MEDIA_TYPE_PNG, f));
                    }
                }
                if (mHashMapBarcode != null) {

                    final List<Integer> list_key = toHashKeyOrList(mHashMapBarcode);
                    for (int i = 0; i < mHashMapBarcode.size(); i++) {
                        File f = new File(mHashMapBarcode.get(list_key.get(i)));
//                        Bitmap bitmap=BitmapFactory.decodeFile(f.getAbsolutePath());
                        builder.addFormDataPart("pic2", f.getName(), RequestBody.create(OkHttpEngine.MEDIA_TYPE_PNG, f));
                    }
                }


                builder.addFormDataPart("gname", mActivityUploadShowProductNameText.getText().toString().trim());
                builder.addFormDataPart("gstandard", mActivityUploadShowProductSizeText.getText().toString().trim());
                builder.addFormDataPart("gprice", mActivityUploadShowProductPriceText.getText().toString().trim());
                builder.addFormDataPart("gtid", String.valueOf(gid));
                builder.addFormDataPart("gbarcode", mActivityUploadShowProductBarcodeTextText.getText().toString().trim());
                builder.addFormDataPart("sid", String.valueOf(loginBean.getExtend().getShop().getSid()));

                MultipartBody requestBody = builder.build();

                OkHttpEngine.getInstance().sendMultipartCall(CONSTS.HOST + CONSTS.REMOTEADD, requestBody).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(UploadActivity.this, R.string.network_failure + "---->" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        final UpLoadBean upLoadBean = new Gson().newBuilder().create().fromJson(result, UpLoadBean.class);
                        Log.d(TAG, "onResponse: r " + result);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (upLoadBean.getCode() == 100) {
                                    Toast.makeText(UploadActivity.this, R.string.network_success, Toast.LENGTH_SHORT).show();
                                    mActivityUploadShowProductNameText.setText("");
                                    mActivityUploadShowProductSizeText.setText("");
                                    mActivityUploadShowProductPriceText.setText("");
                                    mActivityUploadShowProductBarcodeTextText.setText("");
                                    mHashMap.clear();
                                    mHashMapBarcode.clear();
                                    toAdapter(mHashMap);
                                    toAdapterBarCode(mHashMapBarcode);
                                } else
                                    Toast.makeText(UploadActivity.this, R.string.network_failure, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
                break;
            case R.id.image_activity_upload_show_product_photo:// TODO 18/11/29
                showPopupWindow(v, R.id.image_activity_upload_show_product_photo);
                break;
            case R.id.image_activity_upload_show_product_barcode:// TODO 18/11/29
                showPopupWindow(v, R.id.image_activity_upload_show_product_barcode);
                break;
            default:
                break;
        }
    }

    private void showPopupWindow(View v, final int id) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_window, null);
        // 设置按钮的点击事件
        Button button = (Button) contentView.findViewById(R.id.pop_bt1);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // num = 1;
                // intoActivity(ReportPhotosActivity.class);
                Intent into = new Intent(UploadActivity.this,
                        ReportPhotosActivity.class);
                switch (id) {
                    case R.id.image_activity_upload_show_product_photo:
                        startActivityForResult(into, CONSTS.GET_IMAGE_PHOTO_ALBUM);
                        break;
                    case R.id.image_activity_upload_show_product_barcode:
                        startActivityForResult(into, CONSTS.GET_IMAGE_PHOTO_ALBUM_BARCODE);
                        break;
                }

                popupWindow.dismiss();

            }
        });
        Button button2 = (Button) contentView
                .findViewById(R.id.pop_bt2);
        button2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO popwindow点击监听
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                    try {
                        // num = 2;
                        File dir = new File(Environment
                                .getExternalStorageDirectory()
                                + "/"
                                + localTempImgDir);
                        if (!dir.exists())
                            dir.mkdirs();

                        Intent intent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        localTempImgFileName = SystemClock
                                .currentThreadTimeMillis() + ".jpg";
                        File f = new File(dir, localTempImgFileName);// localTempImgDir和localTempImageFileName是自己定义的名字
                        Uri u = Uri.fromFile(f);
                        intent.putExtra(
                                MediaStore.Images.Media.ORIENTATION, 0);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                        Log.d(TAG, "onClick: "+1111);
                        switch (id) {
                            case R.id.image_activity_upload_show_product_photo:
                                startActivityForResult(intent,
                                        CONSTS.GET_IMAGE_VIA_CAMERA);
                                break;
                            case R.id.image_activity_upload_show_product_barcode:
                                startActivityForResult(intent,
                                        CONSTS.GET_IMAGE_VIA_BARCODE);
                                break;
                        }
                        Log.d(TAG, "onClick: "+2222 );
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(UploadActivity.this, R.string.environment_exception, Toast.LENGTH_LONG)
                                .show();
                    } catch (Exception e){
                        Toast.makeText(UploadActivity.this, ""+e.getMessage(), Toast.LENGTH_LONG)
                                .show();
                    }
                } else {
                    Toast.makeText(UploadActivity.this, R.string.not_Environment, Toast.LENGTH_LONG).show();
                }
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                true);
        popupWindow.setWidth(200);
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.buy_btn_normal1));

        // 设置好参数之后再show
        popupWindow.showAsDropDown(v);

    }

    @SuppressLint("UseSparseArrays")
    @SuppressWarnings("static-access")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == this.RESULT_OK) {

            if (requestCode == CONSTS.GET_IMAGE_VIA_CAMERA) {
                // try {
                File f = new File(Environment.getExternalStorageDirectory()
                        + "/" + localTempImgDir + "/" + localTempImgFileName);
                try {
                    MediaStore.Images.Media.insertImage(this.getContentResolver(), f.getAbsolutePath(), "title", "description");
                    this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + f.getAbsolutePath())));
                } catch (FileNotFoundException e) {
//					Toast.makeText(getActivity(),"",Toast.LENGTH_SHORT).show();
                }
                // Intent i = new Intent("com.android.camera.action.CROP");
                // i.setType("image/*");
                // // i.putExtra("data", bb);
                // i.setDataAndType(Uri.fromFile(f), "image/jpeg");
                // i.putExtra("crop", "true");
                // i.putExtra("aspectX", 1);
                // i.putExtra("aspectY", 1);
                // i.putExtra("outputX", 500);
                // i.putExtra("outputY", 500);
                // i.putExtra("return-data", true);
                // this.startActivityForResult(i, 7);
                // } else if (requestCode == 7) {
                // Bitmap bb = data.getParcelableExtra("data");
                // Uri就是拍摄获得的原始图片的uri，
                //
                // Uri u = Uri.parse(android.provider.MediaStore.Images.Media
                // .insertImage(getContentResolver(),
                // f.getAbsolutePath(), null, null));

                mHashMap = new HashMap<Integer, String>();
                mHashMap.put(1, f.getAbsolutePath());

                toAdapter(mHashMap);
                return;
                // } catch (FileNotFoundException e) {
                // e.printStackTrace();
                // }
            } else if (requestCode == CONSTS.GET_IMAGE_PHOTO_ALBUM) {
                mHashMap = (Map<Integer, String>) data.getExtras().get("datas");
                initVariable(mHashMap);
                return;
            } else if (requestCode == CONSTS.GET_IMAGE_VIA_BARCODE) {
                File f = new File(Environment.getExternalStorageDirectory()
                        + "/" + localTempImgDir + "/" + localTempImgFileName);
                try {
                    MediaStore.Images.Media.insertImage(this.getContentResolver(), f.getAbsolutePath(), "title", "description");
                    this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + f.getAbsolutePath())));
                } catch (FileNotFoundException e) {
                }
                mHashMapBarcode = new HashMap<Integer, String>();
                mHashMapBarcode.put(1, f.getAbsolutePath());

                toAdapterBarCode(mHashMapBarcode);
                return;
            } else if (requestCode == CONSTS.GET_IMAGE_PHOTO_ALBUM_BARCODE) {
                mHashMapBarcode = (Map<Integer, String>) data.getExtras().get("datas");
                initVariableBarCode(mHashMapBarcode);
                return;
            }

            IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (scanResult != null) {
                String result = scanResult.getContents();
                Toast.makeText(this, "", Toast.LENGTH_LONG).show();
                if (!TextUtils.isEmpty(result))
                    mActivityUploadShowProductBarcodeTextText.setText(result);
            }
        }

    }

    private void initVariable(Map<Integer, String> map) {
        mHashMap = map;
        if (mHashMap != null) {
            toAdapter(mHashMap);
        }
    }

    private void initVariableBarCode(Map<Integer, String> map) {
        mHashMapBarcode = map;
        if (mHashMapBarcode != null) {
            toAdapterBarCode(mHashMapBarcode);
        }
    }

    private void toAdapter(Map<Integer, String> creame_map) {
//        photos_gv = (GridView) findViewById(R.id.report_gv_photos);
        Photos_Gv_Report_Adapter pgra = new Photos_Gv_Report_Adapter(
                creame_map, this, toHashKeyOrList(creame_map));
        photos_gv.setAdapter(pgra);
    }

    private void toAdapterBarCode(Map<Integer, String> creame_map) {
        if (creame_map != null) {
            final Photos_Gv_Report_Adapter pgra = new Photos_Gv_Report_Adapter(
                    creame_map, this, toHashKeyOrList(creame_map));
            photos_gv_barcode.setAdapter(pgra);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (mHashMapBarcode != null) {
                        final List<Integer> list_key = toHashKeyOrList(mHashMapBarcode);
                        for (int i = 0; i < mHashMapBarcode.size(); i++) {
                            File f = new File(mHashMapBarcode.get(list_key.get(i)));
                            final Result result = scanningImage(f.getAbsolutePath());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (result != null) {
                                        mActivityUploadShowProductBarcodeTextText.setText(result.getText());
                                        Toast.makeText(UploadActivity.this, "" + mActivityUploadShowProductBarcodeTextText.getText().toString(), Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(UploadActivity.this, R.string.barcode_fail_msg, Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        }
                    }
                }
            }).start();


        }

    }

    public static List<Integer> toHashKeyOrList(Map<Integer, String> mHashMap2) {
        return new ArrayList<Integer>(mHashMap2.keySet());
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.spinner_activity_upload_show_product_type_list:
                GoodStype.ExtendBean.GoodsTypesBean goodsTypesBean = (GoodStype.ExtendBean.GoodsTypesBean) parent.getAdapter().getItem(position);
//                Toast.makeText(this, "" + goodsTypesBean.getGtid(), Toast.LENGTH_SHORT).show();
                OkHttpEngine.getInstance().getAsynHttp(CONSTS.HOST + CONSTS.LISTBYPARENTID + "?parent_id=" + goodsTypesBean.getGtid(), UploadActivity.this).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(UploadActivity.this, R.string.get_type_list, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String result = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!TextUtils.isEmpty(result)) {
                                    Gson gson = new GsonBuilder().create();
                                    GoodStype goodStype = gson.fromJson(result, GoodStype.class);
                                    GoodStype.ExtendBean extendBean = goodStype.getExtend();
                                    List<GoodStype.ExtendBean.GoodsTypesBean> goodsTypesBeanList = extendBean.getGoods_Types();
                                    Array_Adapter array_adapter = new Array_Adapter(goodsTypesBeanList, UploadActivity.this);
                                    mActivityUploadShowVarietiesTypeListSpinner.setAdapter(array_adapter);
                                } else {
                                    Toast.makeText(UploadActivity.this, R.string.result_data_null, Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
                break;
            case R.id.spinner_activity_upload_show_varieties_type_list:
                GoodStype.ExtendBean.GoodsTypesBean goodsTypesBeans = (GoodStype.ExtendBean.GoodsTypesBean) parent.getAdapter().getItem(position);
                this.gid = goodsTypesBeans.getGtid();
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    /**
     * 扫描二维码图片的方法,返回结果
     *
     * @param path
     * @return 返回结果
     */
    public Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
        hints.put(DecodeHintType.TRY_HARDER, "UTF8"); // 设置二维码内容的编码
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取原大小
        Bitmap scanBitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false; // 获取新的大小
        int sampleSize = (int) (options.outHeight / (float) 100);
        if (sampleSize <= 0)
            sampleSize = 1;
        options.inSampleSize = sampleSize;

        //获取到bitmap对象(相册图片对象通过path)
        scanBitmap = BitmapFactory.decodeFile(path, options);
        //输入bitmap解析的二值化结果(就是图片的二进制形式)
        int[] data = new int[scanBitmap.getWidth() * scanBitmap.getHeight()];
        scanBitmap.getPixels(data, 0, scanBitmap.getWidth(), 0, 0, scanBitmap.getWidth(), scanBitmap.getHeight());
        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap.getWidth(), scanBitmap.getHeight(), data);
        //再把图片的二进制形式转换成,图片bitmap对象
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        //CodaBarReader codaBarReader= new CodaBarReader();    //codaBarReader  二维码
        try {
            return new MultiFormatReader().decode(bitmap1, hints);      //识别条形码
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
